//
//  NewNoteView.swift
//  WYYao
//
//  Created by wangcl on 2024/9/12.
//

import SwiftUI

struct NewNoteView: View {
    @State var title:String = ""
    @State var content:String = ""
    @Binding var showNoteView:Bool
    @State private var isEditing = false
    @Binding var noteItems:[NoteItem]
    
    @State var showToast = false
    @State var toastMessage = ""
    
    var body: some View {
        NavigationView(content: {
            VStack(content: {
                Divider()
                TextField("请输入标题",text: $title,onEditingChanged: { editingChange in
                    self.isEditing = editingChange
                }).padding()
                Divider()
                ZStack(alignment:.topLeading,content: {
                    TextEditor(text: $content).font(.system(size: 17)).padding()
                    if content.isEmpty {
                        Text("请输入内容")
                            .foregroundColor(Color(UIColor.placeholderText))
                            .padding(20)
                    }
                })
            }).navigationTitle("新建笔记")
              .navigationBarTitleDisplayMode(.inline)
              .toolbar(content: {
                  ToolbarItem(placement: .navigationBarLeading) {
                      Button(action: {
                          showNoteView.toggle()
                      }, label: {
                          Image(systemName: "xmark.circle.fill")
                              .font(.system(size: 17))
                              .foregroundColor(.gray)
                      })
                  }
                  ToolbarItem(placement: .navigationBarTrailing) {
                      Button(action: {
                          if isNull(text: title) {
                              self.toastMessage = "请输入标题"
                              self.showToast = true
                          } else if isNull(text: content) {
                              self.toastMessage = "请输入内容"
                              self.showToast = true
                          } else {
                              addNote(writeTime: Tools.getCurrentTime(), title: title, content: content)
                              showNoteView.toggle()
                          }
                      }, label: {
                          Text("完成").font(.system(size: 17))
                      })
                  }
              })
              .toast(present: $showToast, message: $toastMessage)
              
        })
    }
    func isNull(text:String) -> Bool {
        if text == "" {
                return true
            }
            return false
    }
    // 新建笔记
    func addNote(writeTime:String,title:String,content:String){
        let note = NoteItem(writeTime: writeTime, title: title, content: content)
        noteItems.append(note)
    }
}

#Preview {
    @State var showNote = true
    return NewNoteView(title: "",content: "",showNoteView: $showNote,noteItems: .constant([]))
}
